from re import split
import os, sys

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from monitoring import sh, get_mysql_data_management

TABLE = 'item_records'

db1 = get_mysql_data_management()
db2 = get_mysql_data_management()


def df(item_id: int, cmd: str) -> dict:
    """查询指定服务器硬盘使用，执行用户具有sudo权限，集群之间root用户可免密登录"""
    print(cmd)
    result = sh.evaluate(cmd)
    now = sh.now
    dt = {k: v for k, v in zip(*(split(r'\s+', line) for line in result.split('\n')))}
    print(dt)
    return {
        'item_id': item_id,
        'monitoring_time': now,
        'monitoring_value': int(dt['Used']),
    }


def df_total(item_id: int, cmd: str) -> dict:
    """查询指定服务器硬盘容量，执行用户具有sudo权限，集群之间root用户可免密登录"""
    print(cmd)
    result = sh.evaluate(cmd)
    now = sh.now
    dt = {k: v for k, v in zip(*(split(r'\s+', line) for line in result.split('\n')))}
    print(dt)
    return {
        'item_id': item_id,
        'monitoring_time': now,
        'monitoring_value': int(dt['1K-blocks']),
    }


def df_available(item_id: int, cmd: str) -> dict:
    """查询指定服务器硬盘剩余，执行用户具有sudo权限，集群之间root用户可免密登录"""
    print(cmd)
    result = sh.evaluate(cmd)
    now = sh.now
    dt = {k: v for k, v in zip(*(split(r'\s+', line) for line in result.split('\n')))}
    print(dt)
    return {
        'item_id': item_id,
        'monitoring_time': now,
        'monitoring_value': int(dt['Available']),
    }


def run_df():
    """批量写入MySQL"""
    for item_id, cmd in db1.fetchone('SELECT item_id,item_cmd FROM item_info WHERE item_type="服务器硬盘使用"'):
        dt = df(item_id, cmd)
        db2.insert(dt, TABLE)


def run_df_total():
    """批量写入MySQL"""
    for item_id, cmd in db1.fetchone('SELECT item_id,item_cmd FROM item_info WHERE item_type="服务器硬盘总量"'):
        dt = df_total(item_id, cmd)
        db2.insert(dt, TABLE)


def run_df_available():
    """批量写入MySQL"""
    for item_id, cmd in db1.fetchone('SELECT item_id,item_cmd FROM item_info WHERE item_type="服务器硬盘剩余"'):
        dt = df_available(item_id, cmd)
        db2.insert(dt, TABLE)


if __name__ == '__main__':
    run_df()
    run_df_total()
    run_df_available()
